#include "lua_path.h"
#include "lua_utils.h"
#include <string>
#include "Win32Utils/CPathUtils.h"
#include "Win32Utils/CStrUtils.h"

static luaL_Reg lib_functions[] =
{
    { "get_path_info", &lua_path::get_path_info},
    { "get_path_list", &lua_path::get_path_list},
    { NULL, NULL}
};

void lua_path::initialize(lua_State* L, const char* lib_name)
{
    lua_newtable(L);

    luaL_Reg* fun_info = lib_functions;
    while (fun_info->func)
    {
        lua_pushcfunction(L, fun_info->func);
        lua_setfield(L, -2, fun_info->name);
        fun_info++;
    }
    lua_setfield(L, -2, lib_name);
}

void lua_path::uninitialize()
{

}

int lua_path::get_path_info(lua_State* L)
{
    int nTop = lua_gettop(L);
    _tstring strPath;

    if (nTop >= 1 && lua_isstring(L, 1))
    {
        strPath = lua_tostring(L, 1);
    }

    lua_newtable(L);

    lua_utils::set_key_value(L, "driver", CPathUtils::GetFileDriver(strPath));
    lua_utils::set_key_value(L, "dir", CPathUtils::GetFileDir(strPath));
    lua_utils::set_key_value(L, "ext", CPathUtils::GetFileExt(strPath));
    lua_utils::set_key_value(L, "name", CPathUtils::GetFileName(strPath, false));
    lua_utils::set_key_value(L, "size", (double)CPathUtils::GetFileSize(strPath));
    lua_utils::set_key_value(L, "attr", (int)CPathUtils::GetAttributes(strPath));

    return 1;
}

int lua_path::get_path_list(lua_State* L)
{
    int nTop = lua_gettop(L);
    _tstring strPath;
    int depth = MAX_PATH;
    DWORD dwExclude = 0;
    DWORD dwContain = 0;

    if (nTop >= 1 && lua_isstring(L, 1))
    {
        strPath = lua_tostring(L, 1);
    }

    if (nTop >= 2 && lua_isnumber(L, 2))
    {
        depth = lua_tointeger(L, 2);
    }

    if (nTop >= 3 && lua_isnumber(L, 3))
    {
        dwExclude = lua_tointeger(L, 3);
    }

    if (nTop >= 4 && lua_isnumber(L, 4))
    {
        dwContain = lua_tointeger(L, 4);
    }

    std::vector<_tstring> fileList = CPathUtils::GetFileList(strPath, depth, dwExclude, dwContain);

    lua_createtable(L, fileList.size(), 1);
    int index = 1;
    for (const auto& item : fileList)
    {
        lua_pushstring(L, item.c_str());
        lua_rawseti(L, -2, index++);
    }

    return 1;
}
